import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:tx_live_plugin/widget/tx_live_play.dart';
import 'package:tx_live_plugin_example/util/click.dart';
import 'package:tx_live_plugin_example/widget/life_state.dart';

///直播推流视频的播放
class PlayPage extends StatefulWidget {
  final List<String> urls;

  const PlayPage({Key? key, required this.urls}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _PlayPageState();
}

class _PlayPageState extends LifeState<PlayPage> {
  late _PlayModel _playModel;

  @override
  void initState() {
    _playModel = _PlayModel(widget.urls);
    _playModel.addListener(() {
      if (mounted) setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: InkWell(
              onTap: () => Navigator.pop(context),
              child: const Icon(Icons.arrow_back_ios_rounded, size: 18)),
          title: const Text("视频播放")),
      body: Stack(
        children: [
          Positioned.fill(child: Container(color: Colors.black38)),
          Positioned.fill(child: TxLivePlay(controller: _playModel._controller, callback: _playModel),),
          Align(alignment: Alignment.bottomCenter, child: _switchPlayBtn()),
          Align(alignment: Alignment.bottomCenter, child: _seekBar()),
          Align(
              alignment: Alignment.topCenter,
              child: Visibility(
                  visible: _playModel.isLoading,
                  child: const CupertinoActivityIndicator()))
        ],
      ),
    );
  }

  @override
  void onPaused() {
    _playModel.onPause();
    super.onPaused();
  }

  @override
  void onResumed() {
    _playModel.onResume();
    super.onResumed();
  }

  @override
  void dispose() {
    _playModel.onDestroy();
    super.dispose();
  }

  Widget _switchPlayBtn() {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(30),
          child: Click(
            onTap: _playModel.switchPlay,
            child: _playModel.isPlaying
                ? const Icon(Icons.pause_circle_filled,
                    color: Colors.redAccent, size: 60)
                : const Icon(Icons.play_circle_fill_rounded,
                    color: Colors.redAccent, size: 60),
          ),
        ),
      ),
    );
  }

  Widget _seekBar() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 65),
      child: SizedBox(
        height: 15 + 35,
        width: double.infinity,
        child: Row(
          children: [
            const SizedBox(width: 8),
            Text(_playModel.textStart,
                style: const TextStyle(color: Colors.white)),
            Expanded(
                child: Slider(
              value: _playModel.currentSliderValue,
              max: _playModel.maxSliderValue,
              //divisions: 5,
              label: _playModel.currentSliderValue.round().toString(),
              onChanged: _playModel.onSliderChanged,
              onChangeEnd: _playModel.onSliderChangedEnd,
              onChangeStart: _playModel.onSliderChangedStart,
            )),
            Text(_playModel.textDuration,
                style: const TextStyle(color: Colors.white)),
            const SizedBox(width: 8),
          ],
        ),
      ),
    );
  }
}

class _PlayModel with ChangeNotifier, PlayCallback {
  final PlayController _controller = PlayController();
  var isLoading = false;
  var isPlaying = false;
  var textStart = "00:00";
  var textDuration = "00:00";
  List<String> urls;
  double currentSliderValue = 0;
  double maxSliderValue = 0;
  bool _isSlideStart = false;
  Timer? _timer;

  _PlayModel(this.urls);

  onResume() {
    _controller.onResume();
  }

  onPause() {
    _controller.onPause();
  }

  onDestroy() {
    _controller.onDestroy();
  }

  switchPlay() async{
    print("switchPlay 点击播放");
    await _controller.switchPlay(urls);
    isPlaying = await _controller.isPlaying();
    notifyListeners();
  }

  void onSliderChangedStart(double value) {
    _isSlideStart = true;
  }

  void onSliderChangedEnd(double value) {
    //进度条 以毫秒的时间单位作为max，android的播放进度 以秒为准
    _controller.seek(value ~/ 1000);
    _isSlideStart = false;
  }

  void onSliderChanged(double value) {
    currentSliderValue = value;
    notifyListeners();
  }

  @override
  toast(String? msg) {
    Fluttertoast.showToast(msg: msg??'');
  }

  @override
  error(String? msg) {
    Fluttertoast.showToast(msg: msg??'');
  }

  @override
  Future<bool> checkPlayForNotWifi() {
    //当前 网络状态不是wifi，是否继续播放，true继续播放
    return Future.value(true);
  }

  @override
  startLoading(bool showLoading) {
    isLoading = showLoading;
    notifyListeners();
  }


  @override
  playProcess({int? progress, int? duration, int? playable, String? startTime, String? durationTime}) {
    if(_isSlideStart)return;
    currentSliderValue = (progress??0).toDouble();
    if(progress == 0 && duration == null){
      //播放结束
      textStart = "00:00:00";
    }else {
      maxSliderValue = (duration??0).toDouble();
      textStart = startTime??'';
      textDuration = durationTime??'';
    }
    //设置间隔刷新
    if(_timer?.isActive == true)return;
    _timer?.cancel();
    _timer = Timer(const Duration(milliseconds: 200),(){
      notifyListeners();
      _timer?.cancel();
      _timer = null;
    });
  }


  @override
  backStartPlay(bool start) async{
    // isPlaying = await _controller.isPlaying();
    // notifyListeners();
  }

  @override
  playStatus(int? status) async{
    isPlaying = await _controller.isPlaying();
    notifyListeners();
  }
}
